package com.yanxin.credit.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yanxin.credit.dto.AmazonOrderDTO;
import com.yanxin.credit.dto.LoginUserDTO;
import com.yanxin.credit.dto.PageDataInfo;
import com.yanxin.credit.entity.AmazonOrder;
import com.yanxin.credit.mapper.AmazonOrderMapper;
import com.yanxin.credit.mapstruct.AmazonOrderStruct;
import com.yanxin.credit.service.IAmazonOrderService;
import com.yanxin.credit.service.TokenService;
import com.yanxin.credit.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AmazonOrderServiceImpl extends ServiceImpl<AmazonOrderMapper, AmazonOrder> implements IAmazonOrderService {

    private final AmazonOrderMapper amazonOrderMapper;
    private final AmazonOrderStruct amazonOrderStruct;
    private final TokenService tokenService;

    public AmazonOrderServiceImpl(AmazonOrderMapper amazonOrderMapper,
            AmazonOrderStruct amazonOrderStruct,
            TokenService tokenService) {
        this.amazonOrderMapper = amazonOrderMapper;
        this.amazonOrderStruct = amazonOrderStruct;
        this.tokenService = tokenService;
    }

    @Override
    public AmazonOrder insertOrder(AmazonOrderDTO orderDTO) {
        AmazonOrder order = amazonOrderStruct.toEntity(orderDTO);
        LoginUserDTO loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        if (ObjectUtil.isNull(order.getId())) {
            order.setCreateTime(new Date());
            order.setCreateUser(loginUser.getUser().getId().toString());
        }
        order.setUpdateTime(new Date());
        order.setUpdateUser(loginUser.getUser().getId().toString());

        saveOrUpdate(order);
        return order;
    }

    @Override
    public int deleteOrder(long orderId) {
        return amazonOrderMapper.deleteById(orderId);
    }

    @Override
    public PageDataInfo listBySelective(Date orderDate, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<AmazonOrder> query = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(orderDate)) {
            query.eq("order_date", orderDate);
        }
        query.orderByDesc("create_time");
        List<AmazonOrder> orders = amazonOrderMapper.selectList(query);
        return new PageDataInfo(orders);
    }
}